<template>
    <el-dialog v-model="visible" title="外出登记审核" width="420px" :close-on-click-modal="false" draggable>
        <el-descriptions :column="1" border>
            <el-descriptions-item label="客户姓名">{{ record.client.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="外出原因">{{ record.leaveApply.reason || '-' }}</el-descriptions-item>
            <el-descriptions-item label="外出时间">{{ formatDate(record?.leaveApply.leaveTime) }}</el-descriptions-item>
            <el-descriptions-item label="预计返回">{{ formatDate(record?.leaveApply.expectedReturnTime) }}</el-descriptions-item>
            <el-descriptions-item label="办理人">{{ getUserName(record?.leaveApply.applyId) }}</el-descriptions-item>
            <el-descriptions-item label="审批人">{{ getUserName(approveUserId) }}</el-descriptions-item>
            <el-descriptions-item label="审核时间">{{ auditTime }}</el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <el-form :model="auditForm" label-width="90px" style="margin-top: 10px">
            <el-form-item label="审核结果">
                <el-radio-group v-model="auditForm.result">
                    <el-radio label="通过">通过</el-radio>
                    <el-radio label="不通过">不通过</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="auditForm.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="submitAudit" :loading="loading">确认审核</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, inject } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const axios = inject('axios')

const visible = ref(false)
const loading = ref(false)
const record = ref({})
const auditForm = ref({ result: '', remark: '' })
const auditTime = ref('-')
const emit = defineEmits(['refresh'])

const userDict = inject('userDict', {}) // 由父页面 provide

const getUserName = (userId) => {
    if (!userId || !userDict || !userDict.value) return '-'
    return userDict.value[userId]?.username || '未知'
}

const approveUserId = ref(null)

const open = (row) => {
    record.value = row
    auditForm.value = { result: '', remark: '' }
    approveUserId.value = Number(localStorage.getItem('userId')) || null
    auditTime.value = formatDateTime(new Date())
    visible.value = true
}

const formatDate = (str) => {
    if (!str) return '-'
    return str.split(' ')[0]
}
const formatDateTime = (date) => {
    if (!date) return '-'
    const pad = n => n < 10 ? '0' + n : n
    return date.getFullYear() + '-' +
        pad(date.getMonth() + 1) + '-' +
        pad(date.getDate()) + ' ' +
        pad(date.getHours()) + ':' +
        pad(date.getMinutes()) + ':' +
        pad(date.getSeconds())
}

const submitAudit = async () => {
    if (!auditForm.value.result) {
        ElMessage.warning('请选择审核结果')
        return
    }
    loading.value = true
    try {
        const userId = localStorage.getItem('userId')
        const nowTime = formatDateTime(new Date())
        auditTime.value = nowTime

        // 复制 leaveApply 并补充审核字段
        let leaveApply = { ...record.value.leaveApply }
        // 备注内容加括号并追加到 reason
        let oldReason = leaveApply.reason || ''
        if (auditForm.value.remark && auditForm.value.remark.trim()) {
            leaveApply.reason = oldReason + `（${auditForm.value.remark.trim()}）`
        }
        leaveApply.approveId = userId
        leaveApply.approvalStatus = auditForm.value.result
        leaveApply.approvalTime = nowTime

        const { data } = await axios.post('/leaveApply/approval', qs.stringify(leaveApply))
        if (data.status === 200) {
            ElMessage.success('审核成功')
            visible.value = false
            emit('refresh')
        } else {
            ElMessage.warning(data.msg)
        }
    } catch {
        ElMessage.error('审核失败')
    } finally {
        loading.value = false
    }
}

defineExpose({ open })
</script>
